package org.opens.websocket;

import lombok.extern.slf4j.Slf4j;

import javax.websocket.Session;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 功能描述
 *
 * @author: zhangyuming
 * @date: 2023/7/7 11:06
 */
@Slf4j
public class WebsocketManager {

    /**
     * 持有连接
     */
    public static Map<String, Session> sessionMap = new ConcurrentHashMap<>();

    public static Map<String, TelnetClientHolder> telnetClientHolderMap = new ConcurrentHashMap<>();



    /**
     * 根据用户id关闭session
     * @param userId 用户id
     */
    public static void closeSession(String userId) {
        Session session = sessionMap.remove(userId);
        telnetClientHolderMap.get(userId).close();
        try {
            session.close();
        } catch (IOException e) {
            log.error("关闭连接发生异常, 连接id: {}", userId);
        }
    }

    /**
     *
     * @param userId    用户对象
     * @param session   会话session
     */
    public static void newSession(String userId, Session session) {
        sessionMap.put(userId, session);
        TelnetClientHolder telnetClientHolder = new TelnetClientHolder("192.168.1.31", 23, userId);
        telnetClientHolder.registerReadHandle(result -> {
            try {
                session.getBasicRemote().sendText(result);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
        telnetClientHolder.connect();
        telnetClientHolderMap.put(userId, telnetClientHolder);
    }


}
